import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../providers.dart';
import '../../../core/state/universal_state_wrapper.dart';

class HomePage extends ConsumerStatefulWidget {
  const HomePage({super.key});

  @override
  ConsumerState<HomePage> createState() => _HomePageState();
}

class _HomePageState extends ConsumerState<HomePage> {
  @override
  void initState() {
    super.initState();
    Future.microtask(() => ref.read(homeVmProvider.notifier).load());
  }

  @override
  Widget build(BuildContext context) {
    final state = ref.watch(homeVmProvider);

    return Scaffold(
      appBar: AppBar(title: const Text('Home')),
      body: UniversalStateWrapper(
        state: state.pageState,
        onRetry: () => ref.read(homeVmProvider.notifier).load(),
        errorMessage: state.error,
        successBuilder: (ctx) => ListView.separated(
          itemCount: state.items.length,
          separatorBuilder: (_, __) => const Divider(height: 1),
          itemBuilder: (ctx, i) {
            final todo = state.items[i];
            return ListTile(
              title: Text(todo.title),
              trailing: Icon(todo.completed ? Icons.check_circle : Icons.radio_button_unchecked),
            );
          },
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () => ref.read(homeVmProvider.notifier).load(),
        child: const Icon(Icons.refresh),
      ),
    );
  }
}